
<html>

<head>
<title>CS 143 Project 1A</title>
</head>

<h1>Calculator</h1>
<p>(Version 1.0 4/8/2012 by Edwin Wong)<br />
Type a mathematical expression in the following box
(e.g., 10.5+20*3/25)
</p>

<FORM ACTION="calculator.php" METHOD="GET">
<INPUT TYPE="text" NAME="input" VALUE="" SIZE= 20 MAXLENGTH=20>
<INPUT TYPE="submit" VALUE="Calculate">
</FORM>


<body>
<?php
$origExpr = $_GET["input"];

//preg_match returns 0 if pattern not found or 1 if pattern found
$count = @preg_match("/^(\+|\-)?[0-9]+(\.[0-9]+)?(\s*(\+|\-|\/|\*)\s*(\+|\-)?[0-9]+(\.[0-9]+)?)*\s*/",$origExpr, $expr);

echo "<br><br><font size=5><b>RESULT</b></font><br><br>";

//catch division by zero
if(@preg_match("/\/0/", $origExpr, $zero))
{
    echo "ERROR: Division by zero!";
}
elseif(count and $origExpr != "" and $origExpr == $expr[0])
{   
    //eval runs the expression within the "" ""
    if(@eval("\$answer = $expr[0];") === FALSE)
        echo $origExpr." is an INVALID EXPRESSION!";
    else
    {
        echo $origExpr." = ".$answer; 
    }   
}
elseif($origExpr != "") 
    echo $origExpr." is an INVALID EXPRESSION!";
else {}
?>


</body>
</html>
